package org.cy.spring.learning.webchat.websocket;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.util.Enumeration;
import java.util.Map;

/**
 * create date: 2019/10/10 17:04
 *
 * @author cao.yong
 */
public class WebChatHandshake extends HttpSessionHandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        boolean flag = super.beforeHandshake(request, response, wsHandler, attributes);
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request;

            Enumeration<String> names = serverRequest.getServletRequest().getParameterNames();
            while (names.hasMoreElements()) {
                String name = names.nextElement();
                attributes.put(name, serverRequest.getServletRequest().getParameter(name));
            }
        }
        return flag;
    }
}
